package com.xueyi.aixihu.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.StringJoiner;

/**
 * 描述 Office转换的Util对象
 *
 * @auther 俞烨
 * @date 2023-06-28 09
 */
@Slf4j
@Component
public class OfficeConvertUtil {

    @Value("${office.file.path}")
    private String officeFilePath;

    @PostConstruct
    public void initOfficeConvert() {
        FileUtil.mkdir(officeFilePath);
    }

    /**
     * Office转成图片
     *
     * @param officeInputStream
     * @return
     */
    public String convertOfficeToImg(InputStream officeInputStream) {
        return convertPdfToImg(officeInputStream);
    }

    /**
     * 转换PDF=>图片
     *
     * @param pdfInputStream pdf的inputStream流
     * @return 多张图片用，分割
     */
    public String convertPdfToImg(InputStream pdfInputStream) {
        // 解析文档的Doc
        PDDocument pdDocument = null;

        try {
            // 加载IMG信息
            pdDocument = PDDocument.load(pdfInputStream);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            // 获取PDF页数
            int pages = pdDocument.getNumberOfPages();
            log.info("当前PDF的页数为: {}", pages);

            StringJoiner imageJoin = new StringJoiner(",");
            for (int i = 0; i < pages; i++) {

                BufferedImage bufferedImage = renderer.renderImageWithDPI(i, 105);
                File imgFile = new File(officeFilePath + "/" + IdUtil.fastSimpleUUID() + ".png");
                ImageIO.write(bufferedImage, "png", imgFile);
                BufferedInputStream inputStream = FileUtil.getInputStream(imgFile);
                try {
                    imageJoin.add(AliYunOSSUtil.upload(inputStream, imgFile.getName()));
                } finally {
                    inputStream.close();
                    FileUtil.del(imgFile);
                }
                log.info("下载文件{} , 全图片路径为: {} ", i, imageJoin.toString());
            }
            return imageJoin.toString();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("转换PDF异常: {}", e.getMessage());
            return null;
        }
    }
}
